import React from 'react'
// API
import {GetCode} from '../../api/account'
import qs from 'qs'
import {  Button,message } from 'antd';
import {validate_email} from '../../utils/validate'
// 定时器
let timer = null;

export default class  RegisterForm extends React.Component{
    state={
      buttonContent:'获取验证码',
      buttonDisabled:false,
      buttonLoading:false,
      username :this.props.username
    }
    componentWillUnmount(){
      clearInterval(timer)
    }
    
    // changeButtonStatus=()=>{
    //   this.setState({buttonDisabled:false})
    // }
    // 获取验证码
    getCode=()=>{
      let username = this.props.username()
      // 用户名为空就不发送
     if(username&&validate_email(username)){
       
      // const username = this.state.username
      // if(!username){
      //   message.warning('用户名不能为空！')
      //   return false
      // }
      this.setState({
        buttonContent:'发送中',
        buttonLoading:true
      })
      GetCode(username).then(response=>{
        message.success(response.data)
        this.countDown()
        //调用父组件方法打开注册按钮
        this.props.RegisterButton()
      }).catch(error=>{
        this.setState({
          buttonContent:'重新获取',
          buttonDisabled:false,
          buttonLoading:false
        })
        message.warning('请稍后重试')
      })
    }else
        message.warn('用户名填写有误')
    }
    // 按钮60秒倒计时
    countDown=()=>{
      let sec = 5
      this.setState({buttonDisabled:true,buttonLoading:false,buttonContent:sec+'s'})
      timer=setInterval(()=>{
        sec--;
        if(sec<=0){
          this.setState({buttonContent:'重新获取',buttonDisabled:false,buttonLoading:false})
          clearInterval(timer)
          return false
        }
        this.setState({buttonContent:sec+'s'})
      },1000)
    }

    render(){
        return (
            <Button loading={this.state.buttonLoading} disabled={this.state.buttonDisabled} onClick={this.getCode}>{this.state.buttonContent}</Button>
    )
}
}

